package com.ruoyi.hospital.service.order.impl;

import java.math.BigDecimal;
import java.util.List;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.hospital.domain.doctor.DocIncome;
import com.ruoyi.hospital.domain.member.MemberAddress;
import com.ruoyi.hospital.domain.order.ShopOrdersProduct;
import com.ruoyi.hospital.domain.prescriptionInfo.PrescriptionDrug;
import com.ruoyi.hospital.domain.prescriptionInfo.PrescriptionInfo;
import com.ruoyi.hospital.domain.shop.PharmacyDrugSku;
import com.ruoyi.hospital.domain.storeInfo.PharmacyDruginfo;
import com.ruoyi.hospital.domain.vo.OrderDetailVo;
import com.ruoyi.hospital.dto.HotDrug;
import com.ruoyi.hospital.dto.Piedate;
import com.ruoyi.hospital.mapper.doctor.DocIncomeMapper;
import com.ruoyi.hospital.mapper.member.MemberAddressMapper;
import com.ruoyi.hospital.mapper.order.ShopOrdersProductMapper;
import com.ruoyi.hospital.mapper.prescriptionInfo.PrescriptionInfoMapper;
import com.ruoyi.hospital.mapper.shop.PharmacyDrugSkuMapper;
import com.ruoyi.hospital.mapper.shop.ShopOrdersCartMapper;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.mapper.SysConfigMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.hospital.mapper.order.ShopOrdersMapper;
import com.ruoyi.hospital.domain.order.ShopOrders;
import com.ruoyi.hospital.service.order.IShopOrdersService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 商品订单Service业务层处理
 * 
 * @author wendao
 * @date 2024-08-19
 */
@Service
public class ShopOrdersServiceImpl implements IShopOrdersService 
{
    @Autowired
    private ShopOrdersMapper shopOrdersMapper;
    @Autowired
    private ShopOrdersProductMapper shopOrdersProductMapper;
    @Autowired
    private PharmacyDrugSkuMapper pharmacyDrugSkuMapper;
    @Autowired
    private MemberAddressMapper memberAddressMapper;
    @Autowired
    private ShopOrdersCartMapper shopOrdersCartMapper;
    @Autowired
    private PrescriptionInfoMapper prescriptionInfoMapper;
    @Autowired
    private SysConfigMapper sysConfigMapper;
    @Autowired
    private DocIncomeMapper docIncomeMapper;
    /**
     * 查询商品订单
     * 
     * @param id 商品订单主键
     * @return 商品订单
     */
    @Override
    public ShopOrders selectShopOrdersById(Integer id)
    {
        return shopOrdersMapper.selectShopOrdersById(id);
    }

    @Override
    public OrderDetailVo selectShopOrdersByIdFordocincome(Integer id) {
        return shopOrdersMapper.selectShopOrdersByIdFordocincome(id);
    }

    /**
     * 查询商品订单列表
     * 
     * @param shopOrders 商品订单
     * @return 商品订单
     */
    @Override
    public List<ShopOrders> selectShopOrdersList(ShopOrders shopOrders)
    {
        return shopOrdersMapper.selectShopOrdersList(shopOrders);
    }

    /**
     * 新增商品订单
     * 
     * @param shopOrders 商品订单
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertShopOrders(ShopOrders shopOrders)
    {
        //计算 总价
//        BigDecimal orderAmount = new BigDecimal(0);

        shopOrders.setOrderNumber("D"+System.currentTimeMillis());
        shopOrders.setOrderState(0); //待支付
        shopOrders.setCreateTime(DateUtils.getNowTimeSecond());
        int i = shopOrdersMapper.insertShopOrders(shopOrders);

        //添加详细的商品信息
        List<ShopOrdersProduct> shopOrdersProductList = shopOrders.getShopOrdersProductList();
        if(shopOrdersProductList.size()>0){
            for(ShopOrdersProduct shopOrdersProduct : shopOrdersProductList){
                shopOrdersProduct.setOrderId(shopOrders.getId());

                //通过skuid  查询单价，计算总价

                shopOrdersProductMapper.insertShopOrdersProduct(shopOrdersProduct);
            }
        }


        return i;
    }

    /**
     * 修改商品订单
     * 
     * @param shopOrders 商品订单
     * @return 结果
     */
    @Override
    public int updateShopOrders(ShopOrders shopOrders)
    {
        shopOrders.setUpdateTime(DateUtils.getNowTimeSecond());
        return shopOrdersMapper.updateShopOrders(shopOrders);
    }

    @Override
    public int updateShopOrdersForpay(ShopOrders shopOrders) {

        int i = shopOrdersMapper.updateShopOrders(shopOrders);
        /*
        * 医生的提成
        * */
        if(!StringUtils.isNullOrZero(shopOrders.getDocId())){
            SysConfig sysConfig = sysConfigMapper.checkConfigKeyUnique("doc.drug.commission");
            if(sysConfig!=null && sysConfig.getIsListed()==1){   //开启的时候

                DocIncome docIncome = docIncomeMapper.selectDocIncomeBy3(shopOrders.getDocId(), 3, shopOrders.getId());
                if(docIncome==null){
                    docIncome = new DocIncome();
                    docIncome.setDocId(shopOrders.getDocId());
                    docIncome.setIncomeStatus(0); //未结算
                    docIncome.setIncomeType(3);
                    docIncome.setOrderId(shopOrders.getId());
                    docIncome.setOrderPrice(shopOrders.getDrugAmount());
                    docIncome.setCreateTime(DateUtils.getNowTimeSecond());
                    docIncome.setIncomeRate(sysConfig.getConfigValue());
                    docIncome.setIncomeNum(shopOrders.getDrugAmount().multiply(new BigDecimal(sysConfig.getConfigValue())));
                    //收入
                    docIncomeMapper.insertDocIncome(docIncome);
                }
            }
        }

        return i;
    }

    /**
     * 批量删除商品订单
     * 
     * @param ids 需要删除的商品订单主键
     * @return 结果
     */
    @Override
    public int deleteShopOrdersByIds(Integer[] ids)
    {
        return shopOrdersMapper.deleteShopOrdersByIds(ids);
    }

    /**
     * 删除商品订单信息
     * 
     * @param id 商品订单主键
     * @return 结果
     */
    @Override
    public int deleteShopOrdersById(Integer id)
    {
        return shopOrdersMapper.deleteShopOrdersById(id);
    }

    @Override
    public double getNum(Integer drugType) {
        return shopOrdersMapper.getNum(drugType);
    }

    @Override
    public List<Piedate> getStoreData() {
        return shopOrdersMapper.getStoreData();
    }

    @Override
    public List<HotDrug> getHotDrug() {
        return shopOrdersMapper.getHotDrug();
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public ShopOrders purchase(List<PrescriptionDrug> prescriptionDrugs,Integer pid,Integer memberId,BigDecimal  drugPrice) {

        ShopOrders orders = new ShopOrders();
        //根据处方id查询医生id，为医生的药品提成做准备

        PrescriptionInfo prescriptionInfo = prescriptionInfoMapper.selectPreandConById(pid);
        if(prescriptionInfo!=null){
            orders.setDocId(prescriptionInfo.getDocId());
        }

        //2、生成order信息
        orders.setMemberId(memberId);
        orders.setOrderAmount(drugPrice);
        orders.setDrugAmount(drugPrice);
        orders.setOrderState(0);
        orders.setOrderNumber("O"+System.currentTimeMillis());
        orders.setCreateTime(DateUtils.getNowTimeSecond());
        orders.setPid(pid);

        /*
        * 查询默认地址，有就保存
        * */
        MemberAddress  memberAddress = new MemberAddress();
        memberAddress.setMemberId(memberId);
        memberAddress.setIsDefault(1); //必须有默认的
        List<MemberAddress> memberAddresses = memberAddressMapper.selectMemberAddressList(memberAddress);
        if(memberAddresses.size()>0){
            orders.setAddressId(memberAddresses.get(0).getId());
        }

        shopOrdersMapper.insertShopOrders(orders);
        //1、将sku信息 保存到shop_orders_product中
        ShopOrdersProduct shopOrdersProduct = new ShopOrdersProduct();
        for(PrescriptionDrug prescriptionDrug : prescriptionDrugs){
            shopOrdersProduct.setOrderId(orders.getId());
            shopOrdersProduct.setDrugId(prescriptionDrug.getDrugId());
            shopOrdersProduct.setDrugNum(prescriptionDrug.getDrugNum());
            shopOrdersProduct.setSkuId(prescriptionDrug.getSkuId());
            shopOrdersProduct.setDrugPriceTotal(prescriptionDrug.getDrugPriceTotal());
            shopOrdersProductMapper.insertShopOrdersProduct(shopOrdersProduct);
        }

        return orders;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ShopOrders purchaseByStore(ShopOrders shopOrders, Integer memberId) {

        //生成order信息
        ShopOrders orders = new ShopOrders();


        if(StringUtils.isNullOrZero(shopOrders.getAddressId())){
            MemberAddress  memberAddress = new MemberAddress();
            memberAddress.setMemberId(memberId);
            memberAddress.setIsDefault(1); //必须有默认的
            List<MemberAddress> memberAddresses = memberAddressMapper.selectMemberAddressList(memberAddress);
            if(memberAddresses.size()>0){
                orders.setAddressId(memberAddresses.get(0).getId());
            }
        }else{
            orders.setAddressId(shopOrders.getAddressId());
        }


        orders.setOrderAmount(shopOrders.getOrderAmount());
        orders.setDrugAmount(shopOrders.getDrugAmount());
        orders.setFreight(new BigDecimal(0));


        orders.setMemberId(memberId);
        orders.setOrderState(0);
        orders.setOrderNumber("O"+System.currentTimeMillis());
        orders.setCreateTime(DateUtils.getNowTimeSecond());
        shopOrdersMapper.insertShopOrders(orders);

        //获得药品详细信息，报错到 订单药物详情表
        List<ShopOrdersProduct> shopOrdersProductList = shopOrders.getShopOrdersProductList();
        for(ShopOrdersProduct shopOrdersProduct : shopOrdersProductList){
            //根据skuid查询价格
            PharmacyDrugSku pharmacyDrugSku = pharmacyDrugSkuMapper.selectPharmacyDrugSkuById(shopOrdersProduct.getSkuId());
            shopOrdersProduct.setDrugPriceTotal(pharmacyDrugSku.getPrice().multiply(BigDecimal.valueOf(shopOrdersProduct.getDrugNum())));
            shopOrdersProduct.setOrderId(orders.getId());
            shopOrdersProductMapper.insertShopOrdersProduct(shopOrdersProduct);

            //删除购物车信息
            shopOrdersCartMapper.deleteBy(memberId,shopOrdersProduct.getDrugId(),shopOrdersProduct.getSkuId());
        }


        return orders;
    }
}
